package com.huangxt.test.observer;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;

import java.util.Date;
import java.util.Observable;
import java.util.Observer;
@RequiredArgsConstructor
public class MyObserver implements Observer {
    @NonNull
    private String name;
    @NonNull
    private int wait;

    private String article;


    @Override
    public void update(Observable o, Object arg) {
        System.out.println(this.name+"update"+new Date());
        // 更新文章
        updateArticle(o);

    }
    @SneakyThrows
    private void updateArticle(Observable o) {
        Thread.sleep(wait);
        MyObservable myObservable = (MyObservable) o;
        this.article = myObservable.getArticle();
        System.out.printf("我是读者：%s，文章已更新为：%s\n", this.name, this.article);
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new Date());
        MyObservable myObservable = new MyObservable();
        myObservable.addObserver(new MyObserver("a",1000));
        myObservable.addObserver(new MyObserver("b",2000));
        myObservable.addObserver(new MyObserver("c",3000));
        myObservable.publish("什么是观察者模式？");
    }
}
